<template>
  <div class="camara-box" :class="{'is-minimality':isMinimum,'isSmall':containerId == 'phone'} " id="camara-box"
    v-drag="({isInitial,containerId})" @touchstart="touchstart($event, 'camara-box')"
    @touchmove="touchmove($event, 'camara-box')">
    <div class="camara-box-control">
      <div class="control-btn">
        <svg-icon v-show="!isMinimum" icon-class="minus" @click="minimized"></svg-icon>
        <svg-icon v-show="!isInitial" icon-class="frame" @click="initialized"></svg-icon>
        <svg-icon v-show="!isMaximum" icon-class="fullscreen4" @click="maximized('camara-box')"></svg-icon>
        <svg-icon icon-class="close" @click="destroyExit()"></svg-icon>
      </div>
    </div>
    <div class="camara-box-body" v-show="!isMinimum">
      <div class="camara-play-list" :class="`list-${tatalClass}`">
        <div class="camara-box-item" :class="`${tatalClass} ${activeIndex === 0 ? 'is-active': ''}`"
          v-loading="loading[0]" element-loading-text="正在连接..." element-loading-spinner="el-icon-loading"
          element-loading-background="#000000" @click="clickBox(playList[0])">
          <video-box v-if="playList[0] && Object.keys(playList[0]).length > 0" ref="videoBox0" size="medium"
            :hidebinding="hidebinding" :videoID.sync="playList[0].videoID"
            :dispenseable="dispenseable(playList[0].node)" videoIndex="0" :loading.sync="loading[0]"
            @makeCall="makeCall" @videoDistribution="openVideoDistribution" @videoExit="videoExit"></video-box>
          <div class="video-play-box-close" v-show="loading[0]" @click.stop="videoExit(0)">关闭</div>
        </div>
        <div class="camara-box-item" :class="`${tatalClass} ${activeIndex === 1 ? 'is-active': ''}`" v-show="total > 1"
          v-loading="loading[1]" element-loading-text="正在连接..." element-loading-spinner="el-icon-loading"
          element-loading-background="#000000" @click="clickBox(playList[1])">
          <video-box v-if="playList[1] && Object.keys(playList[1]).length > 0" ref="videoBox1" size="medium"
            :hidebinding="hidebinding" :videoID.sync="playList[1].videoID"
            :dispenseable="dispenseable(playList[1].node)" videoIndex="1" :loading.sync="loading[1]"
            @makeCall="makeCall" @videoDistribution="openVideoDistribution" @videoExit="videoExit"></video-box>
          <div class="video-play-box-close" v-show="loading[1]" @click.stop="videoExit(1)">关闭</div>
        </div>
        <div class="camara-box-item" :class="`${tatalClass} ${activeIndex === 2 ? 'is-active': ''}`" v-show="total > 1"
          v-loading="loading[2]" element-loading-text="正在连接..." element-loading-spinner="el-icon-loading"
          element-loading-background="#000000" @click="clickBox(playList[2])">
          <video-box v-if="playList[2] && Object.keys(playList[2]).length > 0" ref="videoBox2" size="medium"
            :hidebinding="hidebinding" :videoID.sync="playList[2].videoID"
            :dispenseable="dispenseable(playList[2].node)" videoIndex="2" :loading.sync="loading[2]"
            @makeCall="makeCall" @videoDistribution="openVideoDistribution" @videoExit="videoExit"></video-box>
          <div class="video-play-box-close" v-show="loading[2]" @click.stop="videoExit(2)">关闭</div>
        </div>
        <div class="camara-box-item" :class="`${tatalClass} ${activeIndex === 3 ? 'is-active': ''}`" v-show="total > 1"
          v-loading="loading[3]" element-loading-text="正在连接..." element-loading-spinner="el-icon-loading"
          element-loading-background="#000000" @click="clickBox(playList[3])">
          <video-box v-if="playList[3] && Object.keys(playList[3]).length > 0" ref="videoBox3" size="medium"
            :hidebinding="hidebinding" :videoID.sync="playList[3].videoID"
            :dispenseable="dispenseable(playList[3].node)" videoIndex="3" :loading.sync="loading[3]"
            @makeCall="makeCall" @videoDistribution="openVideoDistribution" @videoExit="videoExit"></video-box>
          <div class="video-play-box-close" v-show="loading[3]" @click.stop="videoExit(3)">关闭</div>
        </div>
        <div class="camara-box-item" :class="`${tatalClass} ${activeIndex === 4 ? 'is-active': ''}`" v-show="total > 4"
          v-loading="loading[4]" element-loading-text="正在连接..." element-loading-spinner="el-icon-loading"
          element-loading-background="#000000" @click="clickBox(playList[4])">
          <video-box v-if="playList[4] && Object.keys(playList[4]).length > 0" ref="videoBox4" size="medium"
            :hidebinding="hidebinding" :videoID.sync="playList[4].videoID"
            :dispenseable="dispenseable(playList[4].node)" videoIndex="4" :loading.sync="loading[4]"
            @makeCall="makeCall" @videoDistribution="openVideoDistribution" @videoExit="videoExit"></video-box>
          <div class="video-play-box-close" v-show="loading[4]" @click.stop="videoExit(4)">关闭</div>
        </div>
        <div class="camara-box-item" :class="`${tatalClass} ${activeIndex === 5 ? 'is-active': ''}`" v-show="total > 4"
          v-loading="loading[5]" element-loading-text="正在连接..." element-loading-spinner="el-icon-loading"
          element-loading-background="#000000" @click="clickBox(playList[5])">
          <video-box v-if="playList[5] && Object.keys(playList[5]).length > 0" ref="videoBox5" size="medium"
            :hidebinding="hidebinding" :videoID.sync="playList[5].videoID"
            :dispenseable="dispenseable(playList[5].node)" videoIndex="5" :loading.sync="loading[5]"
            @makeCall="makeCall" @videoDistribution="openVideoDistribution" @videoExit="videoExit"></video-box>
          <div class="video-play-box-close" v-show="loading[5]" @click.stop="videoExit(5)">关闭</div>
        </div>
        <div class="camara-box-item" :class="`${tatalClass} ${activeIndex === 6 ? 'is-active': ''}`" v-show="total > 4"
          v-loading="loading[6]" element-loading-text="正在连接..." element-loading-spinner="el-icon-loading"
          element-loading-background="#000000" @click="clickBox(playList[6])">
          <video-box v-if="playList[6] && Object.keys(playList[6]).length > 0" ref="videoBox6" size="medium"
            :hidebinding="hidebinding" :videoID.sync="playList[6].videoID"
            :dispenseable="dispenseable(playList[6].node)" videoIndex="6" :loading.sync="loading[6]"
            @makeCall="makeCall" @videoDistribution="openVideoDistribution" @videoExit="videoExit"></video-box>
          <div class="video-play-box-close" v-show="loading[6]" @click.stop="videoExit(6)">关闭</div>
        </div>
        <div class="camara-box-item" :class="`${tatalClass} ${activeIndex === 7 ? 'is-active': ''}`" v-show="total > 4"
          v-loading="loading[7]" element-loading-text="正在连接..." element-loading-spinner="el-icon-loading"
          element-loading-background="#000000" @click="clickBox(playList[7])">
          <video-box v-if="playList[7] && Object.keys(playList[7]).length > 0" ref="videoBox7" size="medium"
            :hidebinding="hidebinding" :videoID.sync="playList[7].videoID"
            :dispenseable="dispenseable(playList[7].node)" videoIndex="7" :loading.sync="loading[7]"
            @makeCall="makeCall" @videoDistribution="openVideoDistribution" @videoExit="videoExit"></video-box>
          <div class="video-play-box-close" v-show="loading[7]" @click.stop="videoExit(7)">关闭</div>
        </div>
        <div class="camara-box-item" :class="`${tatalClass} ${activeIndex === 8 ? 'is-active': ''}`" v-show="total > 4"
          v-loading="loading[8]" element-loading-text="正在连接..." element-loading-spinner="el-icon-loading"
          element-loading-background="#000000" @click="clickBox(playList[8])">
          <video-box v-if="playList[8] && Object.keys(playList[8]).length > 0" ref="videoBox8" size="medium"
            :hidebinding="hidebinding" :videoID.sync="playList[8].videoID"
            :dispenseable="dispenseable(playList[8].node)" videoIndex="8" :loading.sync="loading[8]"
            @makeCall="makeCall" @videoDistribution="openVideoDistribution" @videoExit="videoExit"></video-box>
          <div class="video-play-box-close" v-show="loading[8]" @click.stop="videoExit(8)">关闭</div>
        </div>

        <div class="camara-box-item" :class="`${tatalClass} ${activeIndex === 9 ? 'is-active': ''}`" v-show="total > 9"
          v-loading="loading[9]" element-loading-text="正在连接..." element-loading-spinner="el-icon-loading"
          element-loading-background="#000000" @click="clickBox(playList[9])">
          <video-box v-if="playList[9] && Object.keys(playList[9]).length > 0" ref="videoBox9" size="medium"
            :hidebinding="hidebinding" :videoID.sync="playList[9].videoID"
            :dispenseable="dispenseable(playList[9].node)" videoIndex="9" :loading.sync="loading[9]"
            @makeCall="makeCall" @videoDistribution="openVideoDistribution" @videoExit="videoExit"></video-box>
          <div class="video-play-box-close" v-show="loading[9]" @click.stop="videoExit(9)">关闭</div>
        </div>
        <div class="camara-box-item" :class="`${tatalClass} ${activeIndex === 10 ? 'is-active': ''}`" v-show="total > 9"
          v-loading="loading[10]" element-loading-text="正在连接..." element-loading-spinner="el-icon-loading"
          element-loading-background="#000000" @click="clickBox(playList[10])">
          <video-box v-if="playList[10] && Object.keys(playList[10]).length > 0" ref="videoBox10" size="medium"
            :hidebinding="hidebinding" :videoID.sync="playList[10].videoID"
            :dispenseable="dispenseable(playList[10].node)" videoIndex="10" :loading.sync="loading[10]"
            @makeCall="makeCall" @videoDistribution="openVideoDistribution" @videoExit="videoExit"></video-box>
          <div class="video-play-box-close" v-show="loading[10]" @click.stop="videoExit(10)">关闭</div>
        </div>
        <div class="camara-box-item" :class="`${tatalClass} ${activeIndex === 11 ? 'is-active': ''}`" v-show="total > 9"
          v-loading="loading[11]" element-loading-text="正在连接..." element-loading-spinner="el-icon-loading"
          element-loading-background="#000000" @click="clickBox(playList[11])">
          <video-box v-if="playList[11] && Object.keys(playList[11]).length > 0" ref="videoBox11" size="medium"
            :hidebinding="hidebinding" :videoID.sync="playList[11].videoID"
            :dispenseable="dispenseable(playList[11].node)" videoIndex="11" :loading.sync="loading[11]"
            @makeCall="makeCall" @videoDistribution="openVideoDistribution" @videoExit="videoExit"></video-box>
          <div class="video-play-box-close" v-show="loading[11]" @click.stop="videoExit(11)">关闭</div>
        </div>
        <div class="camara-box-item" :class="`${tatalClass} ${activeIndex === 12 ? 'is-active': ''}`" v-show="total > 9"
          v-loading="loading[12]" element-loading-text="正在连接..." element-loading-spinner="el-icon-loading"
          element-loading-background="#000000" @click="clickBox(playList[12])">
          <video-box v-if="playList[12] && Object.keys(playList[12]).length > 0" ref="videoBox12" size="medium"
            :hidebinding="hidebinding" :videoID.sync="playList[12].videoID"
            :dispenseable="dispenseable(playList[12].node)" videoIndex="12" :loading.sync="loading[12]"
            @makeCall="makeCall" @videoDistribution="openVideoDistribution" @videoExit="videoExit"></video-box>
          <div class="video-play-box-close" v-show="loading[12]" @click.stop="videoExit(12)">关闭</div>
        </div>
        <div class="camara-box-item" :class="`${tatalClass} ${activeIndex === 13 ? 'is-active': ''}`" v-show="total > 9"
          v-loading="loading[13]" element-loading-text="正在连接..." element-loading-spinner="el-icon-loading"
          element-loading-background="#000000" @click="clickBox(playList[13])">
          <video-box v-if="playList[13] && Object.keys(playList[13]).length > 0" ref="videoBox13" size="medium"
            :hidebinding="hidebinding" :videoID.sync="playList[13].videoID"
            :dispenseable="dispenseable(playList[13].node)" videoIndex="13" :loading.sync="loading[13]"
            @makeCall="makeCall" @videoDistribution="openVideoDistribution" @videoExit="videoExit"></video-box>
          <div class="video-play-box-close" v-show="loading[13]" @click.stop="videoExit(13)">关闭</div>
        </div>
        <div class="camara-box-item" :class="`${tatalClass} ${activeIndex === 14 ? 'is-active': ''}`" v-show="total > 9"
          v-loading="loading[14]" element-loading-text="正在连接..." element-loading-spinner="el-icon-loading"
          element-loading-background="#000000" @click="clickBox(playList[14])">
          <video-box v-if="playList[14] && Object.keys(playList[14]).length > 0" ref="videoBox14" size="medium"
            :hidebinding="hidebinding" :videoID.sync="playList[14].videoID"
            :dispenseable="dispenseable(playList[14].node)" videoIndex="14" :loading.sync="loading[14]"
            @makeCall="makeCall" @videoDistribution="openVideoDistribution" @videoExit="videoExit"></video-box>
          <div class="video-play-box-close" v-show="loading[14]" @click.stop="videoExit(14)">关闭</div>
        </div>
        <div class="camara-box-item" :class="`${tatalClass} ${activeIndex === 15 ? 'is-active': ''}`" v-show="total > 9"
          v-loading="loading[15]" element-loading-text="正在连接..." element-loading-spinner="el-icon-loading"
          element-loading-background="#000000" @click="clickBox(playList[15])">
          <video-box v-if="playList[15] && Object.keys(playList[15]).length > 0" ref="videoBox15" size="medium"
            :hidebinding="hidebinding" :videoID.sync="playList[15].videoID"
            :dispenseable="dispenseable(playList[15].node)" videoIndex="15" :loading.sync="loading[15]"
            @makeCall="makeCall" @videoDistribution="openVideoDistribution" @videoExit="videoExit"></video-box>
          <div class="video-play-box-close" v-show="loading[15]" @click.stop="videoExit(15)">关闭</div>
        </div>
      </div>
      <div class="camara-list">
        <el-tree class="list-tree" ref="listTree" empty-text :data="camaras" node-key="nid" show-checkbox
          highlight-current @check="checkChange" @current-change="currentCamara">
          <el-tooltip class="custom-tree-node" effect="dark" :content="data.label" placement="top-start"
            slot-scope="{ data }" popper-class="custom-tree-node-tooltip-popper">
            <span>{{ data.label }}</span>
          </el-tooltip>
        </el-tree>
      </div>
    </div>
    <div></div>
  </div>
</template>

<script>
import VideoBox from '@/components/Meeting/VideoBox'

import { msgError, msgSuccess, msgWarning } from '@/utils/message'
import playRtsp from '@/utils/webrtc2rtsp'
import screenfull from 'screenfull'
import { forEach } from 'jszip'
export default {
  components: {
    VideoBox,
  },
  props: {
    open: {
      type: Boolean,
      default: false,
    },
    formData: {
      type: Array,
      default: () => {
        return []
      },
    },
    module: {
      type: String,
      default: 'gis',
    },
    // 容器id,拖拽只能在该容器内部
    containerId: {
      type: String,
      default: 'map-container',
    },
    playingData: {
      type: Array,
      default: () => {
        return []
      },
    },
  },
  data() {
    return {
      loading: [
        false,
        false,
        false,
        false,
        false,
        false,
        false,
        false,
        false,
        false,
        false,
        false,
        false,
        false,
        false,
      ],
      playList: [],

      camaras: [],

      hidebinding: false, // 是否隐藏绑定用户, false表示可以显示拨号按钮

      activeIndex: '', // 选中的视频

      isMinimum: false, //最小化
      isMaximum: false, // 最大化
      isInitial: true, // 初始大小
    }
  },
  computed: {
    total() {
      // console.log('total', this.camaras.length)
      return this.camaras.length
    },
    tatalClass() {
      let length = this.camaras.length
      if (length > 9) return 'total_16'
      if (length > 4) return 'total_9'
      if (length > 1) return 'total_4'
      return 'total_1'
    },
  },
  watch: {
    formData: {
      handler(val, old) {
        // console.log('watch formData camaras.length', this.camaras.length)
        if (this.camaras.length === 0) {
          this.camaras = val
        } else {
          // console.log('watch formData')
          val.forEach((item) => {
            if (!this.camaras.find((c) => c.id === item.id)) {
              this.camaras.push(item)
              this.playVideoForCamara(item)
            }
          })
        }
      },
      immediate: true,
    },
    playingData: {
      handler(val) {
        // console.log('watch playingData val', val.length)
        if (!val || val.length === 0) return
        for (let i = 0; i < 16; i++) {
          let el = document.getElementById(`video${i}`)
          if (el) el.play()
        }
      },
      immediate: true,
    },
  },
  methods: {
    // 最小化
    minimized() {
      this.isMinimum = true
      this.isInitial = false
      if (screenfull.isFullscreen) {
        screenfull.exit()
      }
      // 由于拖拽计算是已left和top定位，最小化时在初始窗口大小的左上角，所有要定位到最右下角
      let dragDom = document.getElementById('camara-box')
      dragDom.style.cssText = 'right:0;bottom:0;'
    },
    // 初始大小
    initialized() {
      this.isInitial = true
      this.isMinimum = false
      if (screenfull.isFullscreen) {
        screenfull.exit()
      }
    },
    // 全屏 最大化
    maximized(id) {
      if (!screenfull.isEnabled) {
        msgWarning('浏览器不支持全屏')
        return false
      }
      screenfull.on('change', () => {
        console.log('maximized change', screenfull.isFullscreen)
        if (screenfull.isFullscreen) {
          this.isMaximum = true
          this.isInitial = false
          this.isMinimum = false
        } else {
          this.isMaximum = false
        }
      })

      let div = document.getElementById(id)
      screenfull.toggle(div)
    },
    // 单呼
    makeCall(data) {
      this.$emit('makeCall', data)
    },
    // 设置当前节点选中状态
    setChecked(node, checked = true) {
      this.$nextTick(() => {
        let tree = this.$refs.listTree
        console.log('setChecked', node, checked, tree)
        if (tree) tree.setChecked(node.nid, checked)
      })
    },
    // 点击当前播放窗口
    clickBox(playObj) {
      if (!playObj || Object.keys(playObj).length === 0) return
      let tree = this.$refs.listTree
      if (tree) tree.setCurrentNode(playObj.node)
      this.currentCamara(playObj.node)
    },
    // 当前节点
    currentCamara(camara) {
      console.log('currentCamara', camara)
      let index = this.playList.findIndex(
        (item) => item && item.videoID === camara.id
      )
      if (index !== -1) {
        this.activeIndex = index
        return
      }
      this.activeIndex = ''
    },
    // 选择框勾选
    checkChange(node, checkedData) {
      let checked = checkedData.checkedNodes.includes(node)
      let index = this.playList.findIndex(
        (item) => item && item.videoID === node.id
      )
      if (checked) {
        if (index !== -1) return
        index = this.playList.findIndex(
          (item) => !item || Object.keys(item).length === 0
        )

        if (index === -1) {
          const length = this.playList.length
          if (length >= 16) {
            msgWarning('最多同时查看16方视频')
            return
          } else index = length
        }

        if (node.type === 'userVideo') {
          console.log('用户话机视频', node.label, index)
          this.$set(this.loading, index, true)
          let playObj = { videoID: node.id, node: node }
          this.$set(this.playList, index, playObj)
          this.playVideo(node, node.obj.url, index)
          return
        }

        let obj = node.obj
        if (obj.videoMode === '0') {
          if (!obj.url) {
            msgWarning(`${obj.videoName}摄像头地址为空`)
            return
          }
          this.$set(this.loading, index, true)
          let playObj = { videoID: node.id, node: node }
          this.$set(this.playList, index, playObj)
          this.playVideo(node, obj.url, index, undefined, false)
        } else {
          this.$set(this.loading, index, true)
          let playObj = { videoID: node.id, node: node }
          this.$set(this.playList, index, playObj)
          SDK.openVideo1(obj.videoID)
            .then((res) => {
              this.playVideo(node, res.rtspUrl, index, res.flowID, true)
            })
            .catch((err) => {
              console.log('打开摄像头失败', node.label, index, err)
              msgError('打开摄像头失败')
              this.$set(this.loading, index, false)
              this.setChecked(node, false)
            })
        }
        return
      } else if (index !== -1) {
        this.videoExit(index)
      }
    },
    //  播放视频前处理
    playVideoForCamara(node) {
      console.log('playVideoForCamara', node.label)
      let index = this.playList.findIndex(
        (item) => !item || Object.keys(item).length === 0
      )
      const length = this.playList.length
      if (index === -1) {
        if (length >= 16) {
          msgWarning('最多同时查看16方视频')
          return
        } else index = length
      }

      if (node.type === 'userVideo') {
        console.log('用户话机视频', node.label)
        this.setChecked(node)
        let playObj = { videoID: node.id, node: node }
        this.$set(this.playList, index, playObj)
        this.playVideo(node, node.obj.url, index)
        return
      }

      const obj = node.obj
      if (obj.status === 'st_leave') {
        msgWarning(`${obj.videoName}摄像头不在线`)
        return
      }
      if (obj.videoMode === '0') {
        if (!obj.url) {
          msgWarning(`${obj.videoName}摄像头地址为空`)
          return
        }
        this.$set(this.loading, index, true)
        this.setChecked(node)
        let playObj = { videoID: node.id, node: node }
        this.$set(this.playList, index, playObj)
        this.playVideo(node, obj.url, index, undefined)
      } else {
        this.$set(this.loading, index, true)
        this.setChecked(node)
        let playObj = { videoID: node.id, node: node }
        this.$set(this.playList, index, playObj)
        SDK.openVideo1(obj.videoID)
          .then((res) => {
            this.playVideo(node, res.rtspUrl, index, res.flowID)
          })
          .catch((err) => {
            console.log('打开摄像头失败', err)
            msgError('打开摄像头失败')
            this.$set(this.loading, index, false)
            this.setChecked(node, false)
          })
      }
    },
    //  播放视频前处理
    playVideoBefore() {
      let camaras
      if (this.playingData.length > 0) {
        camaras = []
        this.playingData.forEach((item) => {
          if (item && item.node) {
            camaras.push(item.node)
          } else {
            camaras.push(undefined)
          }
        })
      } else {
        camaras = this.camaras
      }
      let length = camaras.length
      length > 16 ? (length = 16) : ''
      for (let index = 0; index < length; index++) {
        const node = camaras[index]
        if (!node) continue
        if (node.type === 'userVideo') {
          this.setChecked(node)
          let playObj = { videoID: node.id, node: node }
          this.$set(this.playList, index, playObj)

          this.playVideo(node, node.obj.url, index)
          continue
        }
        const obj = node.obj

        if (obj.status === 'st_leave') {
          msgWarning(`${obj.videoName}摄像头不在线`)
          continue
        }
        if (obj.videoMode === '0') {
          if (!obj.url) {
            msgWarning(`${obj.videoName}摄像头地址为空`)
            continue
          }
          this.$set(this.loading, index, true)
          this.setChecked(node)
          let playObj = { videoID: node.id, node: node }
          this.$set(this.playList, index, playObj)
          this.playVideo(node, obj.url, index, undefined)
        } else {
          if (
            this.playList[index] &&
            this.playList[index].videoID === obj.videoID
          )
            continue
          this.$set(this.loading, index, true)
          this.setChecked(node)

          let playObj = { videoID: node.id, node: node }
          this.$set(this.playList, index, playObj)

          SDK.openVideo1(obj.videoID)
            .then((res) => {
              this.playVideo(node, res.rtspUrl, index, res.flowID)
            })
            .catch((err) => {
              console.log('打开摄像头失败', index, err)
              msgError('打开摄像头失败')
              this.$set(this.loading, index, false)
              this.$set(this.playList, index, {})
              this.setChecked(node, false)
            })
        }
      }
    },
    // 播放视频
    playVideo(node, url, index, flowID) {
      let playObj = this.playList[index]
      try {
        if (flowID) playObj.flowID = flowID
        this.$nextTick(() => {
          playObj.rtspNode = playRtsp(
            url,
            `video${index}`,
            this.playVideoCallback
          )
        })
        if (this.module === 'gis') {
          this.$store.commit('GisPlayData', {
            playList: this.playList,
            camaras: this.camaras,
          })
        } else if (this.module === 'meeting') {
          this.$store.commit('MeetPlayData', {
            playList: this.playList,
            camaras: this.camaras,
          })
        } else if (this.module === 'phone') {
          sessionStorage.setItem(
            'phone_linked_video_play_data',
            JSON.stringify({ playList: this.playList, camaras: this.camaras })
          )
        }
      } catch (error) {
        this.videoExit(index)
        msgError('播放失败')
        console.log('播放失败', error)
      }
    },
    // 播放视频回调
    playVideoCallback({ data, event, elId }, rtspNode) {
      let index = Number.parseInt(elId.replace('video', ''))
      if (data) {
        console.log('播放视频回调 打开事件', { data, event, elId })
        if (data.result !== 'succ') {
          msgError('打开摄像头失败')
          this.videoExit(index)
        }
      } else if (event) {
        console.log('播放视频回调 播放事件', event.type)
        if (
          event.type === 'close' &&
          rtspNode === this.playList[index].rtspNode
        ) {
          this.videoExit(index)
        }
      }
    },
    // 退出视频
    videoExit(index, videoID) {
      if (!index && index !== 0) {
        index = this.playList.findIndex((item) => item.videoID === videoID)
        if (index === -1) return
      }
      this.$set(this.loading, index, false)

      let playObj = this.playList[index]
      if (!playObj || Object.keys(playObj).length === 0) return

      if (playObj.rtspNode) {
        clearInterval(playObj.rtspNode.Interval)
        playObj.rtspNode.PC.close()
        if (playObj.flowID) SDK.closeVideo(playObj.videoID, playObj.flowID)
      }

      this.$set(this.playList, index, {})
      this.setChecked(playObj.node, false)

      videoID = playObj.videoID
      if (videoID) {
        // 退出分发
        let old = sessionStorage.getItem(`dispense-${videoID}`)
        if (old) {
          let datas = JSON.parse(old)
          datas.forEach((item) => {
            SDK.stopVideoDispense({
              flowID: item.flowID,
              videoID,
            })
          })
          sessionStorage.removeItem(`dispense-${videoID}`)
        }
      }
      this.closeBox()
    },
    // 关闭所有
    destroyExit() {
      this.playList.forEach((item, index) => {
        this.videoExit(index)
      })
      this.$emit('update:open', false)
      if (this.module === 'gis') {
        this.$store.commit('GisPlayData', null)
      } else if (this.module === 'meeting') {
        this.$store.commit('MeetPlayData', null)
      } else if (this.module === 'phone') {
        sessionStorage.removeItem('phone_linked_video_play_data')
      }
    },
    // 关闭窗口
    closeBox() {
      if (this.camaras.length === 1) {
        this.$emit('update:open', false)
        if (this.module === 'gis') {
          this.$store.commit('GisPlayData', null)
        } else if (this.module === 'meeting') {
          this.$store.commit('MeetPlayData', null)
        } else if (this.module === 'phone') {
          sessionStorage.removeItem('phone_linked_video_play_data')
        }
        return
      }
      if (this.module === 'gis') {
        this.$store.commit('GisPlayData', {
          playList: this.playList,
          camaras: this.camaras,
        })
      } else if (this.module === 'meeting') {
        this.$store.commit('MeetPlayData', {
          playList: this.playList,
          camaras: this.camaras,
        })
      } else if (this.module === 'phone') {
        sessionStorage.setItem(
          'phone_linked_video_play_data',
          JSON.stringify({ playList: this.playList, camaras: this.camaras })
        )
      }
    },
    // 是否能分发
    dispenseable(node) {
      // console.log('是否能分发', node.label, node.obj.videoMode !== '0')
      return node.obj.videoMode !== '0'
    },
    // 打开视频分发窗口
    openVideoDistribution(index) {
      console.log('视频分发')
      let playObj = this.playList[index]
      if (playObj && Object.keys(playObj).length > 0) {
        const node = playObj.node
        this.$emit('videoDistribution', {
          url: node.obj.url,
          videoID: playObj.videoID,
          flowID: playObj.flowID,
        })
      }
    },
    // 实现移动端拖拽
    touchstart(event, elId) {
      console.log('touchstart', elId)
      event.preventDefault()
      let dragDom = document.getElementById(elId)
      let box = document.getElementById(this.containerId)
      //鼠标按下，计算当前元素距离可视区的距离
      let e = event.targetTouches[0]
      const disX = e.clientX
      const disY = e.clientY
      const dragDomWidth = dragDom.offsetWidth
      const dragDomheight = dragDom.offsetHeight
      const screenWidth = box.clientWidth
      const screenHeight = box.clientHeight
      const minDragDomLeft = dragDom.offsetLeft
      const maxDragDomLeft = screenWidth - dragDomWidth - dragDom.offsetLeft
      const minDragDomTop = dragDom.offsetTop
      const maxDragDomTop = screenHeight - dragDomheight - dragDom.offsetTop

      const sty = (function () {
        if (window.document.currentStyle) {
          return (dom, attr) => dom.currentStyle[attr]
        } else {
          return (dom, attr) => getComputedStyle(dom, false)[attr]
        }
      })()
      // 获取到的值带px 正则匹配替换
      let styL = sty(dragDom, 'left')
      let styT = sty(dragDom, 'top')
      // 注意在ie中 第一次获取到的值为组件自带50% 移动之后赋值为px
      if (styL.includes('%')) {
        styL = +screenWidth * (+styL.replace(/\%/g, '') / 100)
        styT = +screenHeight * (+styT.replace(/\%/g, '') / 100)
      } else {
        styL = +styL.replace(/\px/g, '')
        styT = +styT.replace(/\px/g, '')
      }
      let touchDragObj = {
        disX,
        disY,
        minDragDomLeft,
        maxDragDomLeft,
        minDragDomTop,
        maxDragDomTop,
        styL,
        styT,
      }
      elId === 'webrtc-video'
        ? (this.touchDragObj4Webrtc = touchDragObj)
        : (this.touchDragObj = touchDragObj)
    },
    touchmove(event, elId) {
      console.log('touchmove', elId)
      event.preventDefault()
      let touchDragObj =
        elId === 'webrtc-video' ? this.touchDragObj4Webrtc : this.touchDragObj
      let e = event.targetTouches[0]
      //通过事件委托，计算移动的距离
      let left = e.clientX - touchDragObj.disX
      let top = e.clientY - touchDragObj.disY
      // 边界处理
      if (-left > touchDragObj.minDragDomLeft) {
        left = -touchDragObj.minDragDomLeft
      } else if (left > touchDragObj.maxDragDomLeft) {
        left = touchDragObj.maxDragDomLeft
      }

      if (-top > touchDragObj.minDragDomTop) {
        top = -touchDragObj.minDragDomTop
      } else if (top > touchDragObj.maxDragDomTop) {
        top = touchDragObj.maxDragDomTop
      }
      // 移动当前元素
      let dragDom = document.getElementById(elId)
      dragDom.style.cssText += `; left: ${left + touchDragObj.styL}px; top: ${
        top + touchDragObj.styT
      }px;`
    },
  },
  mounted() {
    this.$nextTick(() => {
      this.playVideoBefore()
    })
  },
  destroyed() {
    console.error('destroyed 播放页面')
  },
  directives: {
    drag(el, binding) {
      let dragDom = el //当前元素
      let self = this //上下文
      //禁止选择网页上的文字
      document.onselectstart = function () {
        return false
      }
      const sty = (function () {
        if (window.document.currentStyle) {
          return (dom, attr) => dom.currentStyle[attr]
        } else {
          return (dom, attr) => getComputedStyle(dom, false)[attr]
        }
      })()
      dragDom.onmousedown = function (e) {
        if (screenfull.isFullscreen || !binding.value.isInitial) {
          return
        }

        e.preventDefault()
        let box = document.getElementById(binding.value.containerId)
        //鼠标按下，计算当前元素距离可视区的距离
        const disX = e.clientX
        const disY = e.clientY
        const dragDomWidth = dragDom.offsetWidth
        const dragDomheight = dragDom.offsetHeight
        const screenWidth = box.clientWidth
        const screenHeight = box.clientHeight
        const minDragDomLeft = dragDom.offsetLeft
        const maxDragDomLeft = screenWidth - dragDomWidth - dragDom.offsetLeft
        const minDragDomTop = dragDom.offsetTop
        const maxDragDomTop = screenHeight - dragDomheight - dragDom.offsetTop
        // 获取到的值带px 正则匹配替换
        let styL = sty(dragDom, 'left')
        let styT = sty(dragDom, 'top')
        // 注意在ie中 第一次获取到的值为组件自带50% 移动之后赋值为px
        if (styL.includes('%')) {
          styL = +screenWidth * (+styL.replace(/\%/g, '') / 100)
          styT = +screenHeight * (+styT.replace(/\%/g, '') / 100)
        } else {
          styL = +styL.replace(/\px/g, '')
          styT = +styT.replace(/\px/g, '')
        }
        document.onmousemove = function (e) {
          //通过事件委托，计算移动的距离
          let left = e.clientX - disX
          let top = e.clientY - disY
          // 边界处理
          if (-left > minDragDomLeft) {
            left = -minDragDomLeft
          } else if (left > maxDragDomLeft) {
            left = maxDragDomLeft
          }

          if (-top > minDragDomTop) {
            top = -minDragDomTop
          } else if (top > maxDragDomTop) {
            top = maxDragDomTop
          }
          // 移动当前元素
          dragDom.style.cssText += `; left: ${left + styL}px; top: ${
            top + styT
          }px;`
          console.log('dragDom.style.cssText', dragDom.style.cssText)
        }
        document.onmouseup = function (e) {
          document.onmousemove = null
          document.onmouseup = null
        }
        return false
      }
    },
  },
}
</script>

<style lang="scss" scoped>
@import '~@/assets/scss/camara_box.scss';
</style>